package com.sagereal.wtc.factorymode.Activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.ActionBar;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;

import android.Manifest;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.net.Uri;
import android.os.BatteryManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;

import android.widget.TextView;
import android.widget.Toast;

import com.sagereal.wtc.factorymode.util.Permission;
import com.sagereal.wtc.factorymode.R;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends BaseActivity {
    private boolean mIsExit=false;
    private Timer mTimer;
    private TextView mDeviceInfo,mDeviceModel,mVersion,mAndroidVersion,mRam,mRom,mBatterySize,mScreenSize,mScreenResolution;
    private Button mOpencamera,mCall112,mItemTest,mTestReport;

    private static final int REQUEST_IMAGE_CAPTURE = 1;
    private Uri mPhotoUri;
    private String mCurrentPhotoPath="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//        setTitle(getString(R.string.app_name));

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            // 使用自定义布局
            actionBar.setDisplayShowCustomEnabled(true);
            actionBar.setCustomView(R.layout.custom_action_bar);

            // 设置标题文本
            TextView titleView = findViewById(R.id.action_bar_title);
            titleView.setText(getString(R.string.app_name));
        }
        initView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.title, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(android.view.MenuItem title) {
        if (title.getItemId() == R.id.change) {
            switchLanguage();
            //recreate();  // 重新创建活动以应用新语言
            return true;
        }
        return super.onOptionsItemSelected(title);
    }
    /*切换语言*/
    private void switchLanguage() {
        Resources resources = getResources();
        Configuration configuration = resources.getConfiguration();
        Locale currentLocale = configuration.locale;
        Log.d("MainActivity", "当前语言: " + currentLocale);

        if (currentLocale.equals(Locale.CHINA)|| currentLocale.toString().equals("zh_CN_#Hans")) {
            switchLanguage("chr", "US");
        } else {
            switchLanguage("zh", "CN");
        }
    }

    /*获取权限*/
    @Override
    protected void onStart() {
        super.onStart();
        Permission.checkPermission(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if(Permission.isPermissionGranted(this)) {
            Log.i("PERMISSION","请求权限成功");
        }
    }

    //    授权失败弹出提示框
    @Override
    public void onRequestPermissionsResult(
            int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == Permission.REQUEST_CODE) {
            for (int grantResult : grantResults) {
                if (grantResult != PackageManager.PERMISSION_GRANTED) {
                    Log.e("Permission","授权失败！");
                     //授权失败，弹窗
                    showPermissionDialog();
                    return;
                }
            }
        }
    }

    private void initView(){
        mDeviceInfo = findViewById(R.id.device_info);
        mDeviceModel = findViewById(R.id.device_model);
        mVersion = findViewById(R.id.version);
        mAndroidVersion = findViewById(R.id.android_version);
        mRam = findViewById(R.id.ram);
        mRom = findViewById(R.id.rom);
        mBatterySize = findViewById(R.id.battery_size);
        mScreenSize = findViewById(R.id.screen_size);
        mScreenResolution = findViewById(R.id.screen_resolution);
        mOpencamera = findViewById(R.id.btn_take_photo);
        mCall112 = findViewById(R.id.btn_tel_112);
        mItemTest = findViewById(R.id.btn_item_test);
        mTestReport = findViewById(R.id.btn_test_report);
        updateDeviceInfo();

        /*打开相机拍照*/
        mOpencamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
                        != PackageManager.PERMISSION_GRANTED) {
                    showPermissionDialog();
                } else {
                    // 如果已经有权限，直接启动相机
                    dispatchTakePictureIntent();
                }
            }
        });
        /*拨打电话112*/
        mCall112.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CALL_PHONE)
                        != PackageManager.PERMISSION_GRANTED) {
                    showPermissionDialog();
                } else {
                    // 如果已经有权限，创建打电话的意图
                    Intent intent = new Intent();
                    //设置拨打电话的动作
                    intent.setAction(Intent.ACTION_CALL);
                    //设置拨打电话的号码
                    intent.setData(Uri.parse("tel:" + getString(R.string.phonenum)));
                    //开启打电话的意图
                    startActivity(intent);
                }
            }
        });
        /*跳转单项测试*/
        mItemTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
//                        != PackageManager.PERMISSION_GRANTED ||
//                        ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO)
//                        != PackageManager.PERMISSION_GRANTED) {
//                    showPermissionDialog();
//                } else {
//                }
                Intent intent = new Intent(MainActivity.this, ItemTestActivity.class);
                startActivity(intent);
            }
        });
        /*跳转测试报告*/
        mTestReport.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA)
//                        != PackageManager.PERMISSION_GRANTED ||
//                        ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.RECORD_AUDIO)
//                                != PackageManager.PERMISSION_GRANTED) {
//                    showPermissionDialog();
//                }else {
//                }
                Intent intent = new Intent(MainActivity.this, TestReportActivity.class);
                startActivity(intent);
            }
        });
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            String filePath = getCurrentPhotoPath();
            if (filePath != null) {
                updateGallery(filePath);
            }
            Toast.makeText(this, getString(R.string.photo_save), Toast.LENGTH_SHORT).show();
        } else {
            new File(getCurrentPhotoPath()).deleteOnExit();
        }
    }

    private void dispatchTakePictureIntent() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            // 创建一个文件来保存拍摄的照片
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            if (photoFile != null) {
                mPhotoUri = FileProvider.getUriForFile(this,
                        "com.sagereal.wtc.factorymode.fileprovider",
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mPhotoUri);
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        }
    }

    private File createImageFile() throws IOException {
        // 创建一个唯一的文件名
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
        File image = File.createTempFile(
                imageFileName,  /* 前缀 */
                ".jpg",         /* 后缀 */
                storageDir       /* 目录 */
        );
        // 返回图片的绝对路径
        mCurrentPhotoPath = image.getAbsolutePath();
        return image;
    }

    private void updateGallery(String imagePath) {
        File imgFile = new File(imagePath);
        // 把文件插入到系统图库
        try {
            MediaStore.Images.Media.insertImage(getContentResolver(), imgFile.getAbsolutePath(), imgFile.getName(), null);
        } catch (FileNotFoundException | NullPointerException e) {
            e.printStackTrace();
        }
        // 通知图库更新
        sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + imgFile.getAbsolutePath())));
    }

    public String getCurrentPhotoPath() {
        return mCurrentPhotoPath;
    }

    public void setCurrentPhotoPath(String currentPhotoPath) {
        this.mCurrentPhotoPath = currentPhotoPath;
    }

    /*提示权限需要申请*/
    private void showPermissionDialog() {
        new AlertDialog.Builder(this)
                .setTitle(R.string.permission_ask)
                .setMessage(R.string.permission_content)
                .setNegativeButton(getString(R.string.cancel), null)
                .setPositiveButton(getString(R.string.go_set), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                        Uri uri = Uri.fromParts("package", getPackageName(), null);
                        intent.setData(uri);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                        startActivity(intent);
                    }
                })
                .show();
    }

    /*获取设备信息*/
    private void updateDeviceInfo() {
        mDeviceInfo.setText(Settings.Global.getString(this.getContentResolver(),Settings.Global.DEVICE_NAME));
        mDeviceModel.setText(Build.MODEL);
        mVersion.setText(Build.DISPLAY);
        mAndroidVersion.setText(Build.VERSION.RELEASE);
        mRam.setText(getRAM());
        mRom.setText(getROM(getApplicationContext()));
        mBatterySize.setText(getBattery());
        mScreenResolution.setText(getScreenWidth(MainActivity.this) + getString(R.string.x) + getScreenHeight(MainActivity.this) + getString(R.string.pixel));
        // 获取屏幕尺寸
        float screenSizeInInches = getScreenSizeInInches(MainActivity.this);
        mScreenSize.setText(String.format("%.2f"+getString(R.string.inch), screenSizeInInches));
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        //点击返回键调用方法
        if(keyCode==KeyEvent.KEYCODE_BACK){
            exit();
        }
        return false;
    }
    /*返回键两次*/
    private void exit(){
        if (!mIsExit){
            mIsExit=true;
            Toast.makeText(this,getString(R.string.exit),Toast.LENGTH_SHORT).show();
            mTimer=new Timer();
            mTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    mIsExit=false;
                }
            },2000);
        }else {
            //2000ms内按第二次则退出
            finish();
            System.exit(0);
        }
    }
    /*获取RAM大小*/
    public String getRAM(){
        ActivityManager.MemoryInfo ram = new ActivityManager.MemoryInfo();//获取设备的信息
        ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        activityManager.getMemoryInfo(ram);
        return (int) Math.ceil(ram.totalMem / 1024 / 1024 / (float) 1024) + getString(R.string.g);
    }
    /*获取ROM大小*/
    public static String getROM(Context context) {
        File dataDir = Environment.getDataDirectory();
        long totalSpace = dataDir.getTotalSpace();
        return adjustSize(context, totalSpace);
    }
    /*计算ROM的实际大小*/
    private static String adjustSize(Context context, long size) {
        long adjustedSize;
        String unit = context.getString(R.string.g);
        if (size < 4L * 1024 * 1024 * 1024) {
            adjustedSize = 4;
        } else if (size < 8L * 1024 * 1024 * 1024) {
            adjustedSize = 8;
        } else if (size < 16L * 1024 * 1024 * 1024) {
            adjustedSize = 16;
        } else if (size < 32L * 1024 * 1024 * 1024) {
            adjustedSize = 32;
        } else if (size < 64L * 1024 * 1024 * 1024) {
            adjustedSize = 64;
        } else if (size < 128L * 1024 * 1024 * 1024) {
            adjustedSize = 128;
        } else if (size < 256L * 1024 * 1024 * 1024) {
            adjustedSize = 256;
        } else if (size < 512L * 1024 * 1024 * 1024) {
            adjustedSize = 512;
        } else {
            adjustedSize = size / (1024L * 1024 * 1024); // 转换为TB
            unit = context.getString(R.string.t);
        }
        return adjustedSize + unit;
    }
    /*获取电池大小*/
    public String getBattery(){
        Object powerProfile = null;
        double batteryCapacity = 0;
        try {
            powerProfile = Class.forName("com.android.internal.os.PowerProfile")
                    .getConstructor(Context.class)
                    .newInstance(this);
            batteryCapacity = (double) Class.forName("com.android.internal.os.PowerProfile")
                    .getMethod("getBatteryCapacity")
                    .invoke(powerProfile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if(batteryCapacity == 1000){
            batteryCapacity = 8000;
        }
        return (batteryCapacity+getString(R.string.mah));
    }
    /** 获取当前屏幕的高度 */
    public static int getScreenHeight(Context context) {
        //获取系统服务
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getRealMetrics(dm);  //获取显示参数保存到dm中
        return dm.heightPixels;   //返回屏幕的宽度
    }
    /** 获取当前屏幕的宽度 */
    public static int getScreenWidth(Context context) {
        //获取系统服务
        DisplayMetrics dm = new DisplayMetrics();
        WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        wm.getDefaultDisplay().getRealMetrics(dm);  //获取显示参数保存到dm中
        return dm.widthPixels;   //返回屏幕的宽度
    }
    /*获取屏幕尺寸*/
    public static float getScreenSizeInInches(Context context) {
        DisplayMetrics displayMetrics = new DisplayMetrics();
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        windowManager.getDefaultDisplay().getRealMetrics(displayMetrics);
        float widthInches = displayMetrics.widthPixels / displayMetrics.xdpi;
        float heightInches = displayMetrics.heightPixels / displayMetrics.ydpi;
        return (float) Math.sqrt((widthInches * widthInches) + (heightInches * heightInches));
    }
}